import {serialize} from '@/util/util'
import NProgress from 'nprogress' // progress bar
import errorCode from '@/const/errorCode'
import router from "@/router/router"
import {Message} from 'element-ui'
import 'nprogress/nprogress.css'
import store from "@/store"; 
import qs from "query-string"
axios.defaults.timeout = 30000
// 返回其他状态吗
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500 // 默认的
}

axios.defaults.baseURL = process.env.VUE_APP_BASE_API

// NProgress Configuration
NProgress.configure({
  showSpinner: false
})

// HTTPrequest拦截
axios.interceptors.request.use(config => {
  NProgress.start() // start progress bar
  const isToken = (config.headers || {}).isToken === false
  let token =  store.getters.access_token
  if (token && !isToken) {
    config.headers['access-token'] = token// token
  }
  // 99303a08-2024-40ad-9164-f255cf9b686d

  if (config.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
    config.data = qs.stringify(config.data)
  }

  // headers中配置serialize为true开启序列化
  if (config.methods === 'post' && config.headers.serialize) {
    config.data = serialize(config.data)
    delete config.data.serialize
  }
  return config
}, error => {
  return Promise.reject(error)
})


// HTTPresponse拦截
axios.interceptors.response.use(res => {
  NProgress.done()
  const status = Number(res.data.errno)
  const message = res.data.errmsg || errorCode[status] || errorCode['default']
  // if (status === 401 || status === 10001 || status === 10002) {
  //   store.dispatch('FedLogOut').then(() => {
  //     router.push({path: '/login'})
  //   })
  //   return
  // }
  // if(status!==0){
  //   return Promise.reject(res.data.msg)
  // }
  // if(status === 555){
  //   return res
  // }

  if (status !== 0 && !res.data.hash ) {
    Message({
      message: message,
      type: 'error'
    })
    return Promise.reject(new Error(message))
  }

  return res
}, error => {
  NProgress.done()
  return Promise.reject(new Error(error))
})

export default axios

export const Authorization = 'Bearer ' + store.getters.access_token

export function fetchList (url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {params}).then(res => {
      if (!res) {
        resolve({})
      } else {
        resolve(res.data)
      }
    }).catch(error => {
      reject(error)
    })
  })
}

export function fetchBlob (url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, { responseType: 'blob' }).then(res => {
      if (!res) {
        resolve({})
      } else {
        resolve(res.data)
      }
    }).catch(error => {
      reject(error)
    })
  })
}
  

export function postJson (url, params = {}) {
    return new Promise((resolve, reject) => {
      axios.post(url, {...delEmpty(params)}).then(res => {
        if (!res) {
          resolve({})
        } else {
          resolve(res.data)
        }
      }).catch(error => {
        reject(error)
      })
    })
  }

export function postForm (url, params = {}) {
    return new Promise((resolve, reject) => {
      const headers = {
          'Content-Type': 'application/x-www-form-urlencoded',
        };
      axios.post(url, params, {headers}).then(res => {
        if (!res) {
          resolve({})
        } else {
          resolve(res.data)
        }
      }).catch(error => {
        reject(error)
      })
    })
  }

function delEmpty(obj) {
  const data = {...obj}
  for ( var key in data ){
    if ( data[key] === '' || data[key] === undefined || data[key] === null){
      delete data[key]
    }
  }

  return data;
}
